package cn.summit.core.authentication.handler;

import cn.summit.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义失败处理器
 *
 * @author summit
 * @since 2020/3/4 11:45
 */
@Component("customfailureHandler")
@Slf4j
public class CustomfailureHandler extends SimpleUrlAuthenticationFailureHandler {


    @Autowired
    private SecurityProperties securityProperties;

    /**
     * @param exception 认证失败时抛出异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
        // 认证失败响应JSON字符串，
        // response.setContentType("application/json;charset=UTF-8");
        // response.getWriter().write(JSON.toJSONString(exception.getMessage()));
        // }else {
        //     // 重写向回认证页面，注意加上 ?error
        //     super.setDefaultFailureUrl(securityProperties.getAuthentication().getLoginPage()+"?error");
        //     super.onAuthenticationFailure(request, response, exception);
        // }

        // // 重写向回认证页面，注意加上 ?error
        // super.setDefaultFailureUrl(securityProperties.getAuthentication().getLoginPage()+"?error");
        // super.onAuthenticationFailure(request, response, exception);

        String referer = request.getHeader("Referer");
        log.info("referer:" + referer);

        // 如果下面有值,则认为是多端登录,直接返回一个登录地址
        Object toAuthentication = request.getAttribute("toAuthentication");
        String lastUrl =
            toAuthentication != null ? securityProperties.getAuthentication().getLoginPage()
                : StringUtils.substringBefore(referer, "?");
        log.info("上一次请求的路径 ：" + lastUrl);

        super.setDefaultFailureUrl(lastUrl + "?error");
        super.onAuthenticationFailure(request, response, exception);

    }

}
